<template>
  <div class="connection-manager">
    <el-tabs v-model="activeTab" type="card">
      <el-tab-pane label="设备管理" name="device">
        <!-- 设备管理内容 -->
        <el-table :data="devices" border style="width: 100%; margin-top: 20px;">
          <el-table-column prop="name" label="设备名称" width="180" />
          <el-table-column prop="status" label="连接状态" width="120">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'online' ? 'success' : 'danger'">
                {{ scope.row.status === 'online' ? '在线' : '离线' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="lastActiveTime" label="最后活动时间" width="180" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button-group>
                <el-button 
                  type="primary" 
                  size="small"
                  :disabled="scope.row.status !== 'online'"
                  @click="handleDeviceDetail(scope.row)"
                >
                  详情
                </el-button>
                <el-button 
                  :type="scope.row.status === 'online' ? 'danger' : 'success'"
                  size="small"
                  @click="toggleDeviceStatus(scope.row)"
                >
                  {{ scope.row.status === 'online' ? '断开' : '连接' }}
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="MQTT连接管理" name="mqtt">
        <!-- MQTT管理内容 -->
        <el-table :data="topics" v-loading="loading" border style="width: 100%; margin-top: 20px;">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="topic" label="通道名称" width="180" />
          <el-table-column prop="description" label="描述" width="200" />
          <el-table-column prop="table_name" label="关联表" width="180" />
          <el-table-column prop="active" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.active ? 'success' : 'danger'">
                {{ scope.row.active ? '活跃' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="180">
            <template #default="scope">
              {{ new Date(scope.row.created_at).toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button-group>
                <el-button type="primary" size="small" @click="showEditTopicDialog(scope.row)">
                  编辑
                </el-button>
                <el-button type="danger" size="small" @click="handleDeleteTopic(scope.row)">
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 标签页
const activeTab = ref('device');

// 设备管理相关数据和方法
const devices = ref([
  {
    id: 1,
    name: '油表设备',
    status: 'online',
    lastActiveTime: new Date().toLocaleString()
  }
]);

const toggleDeviceStatus = (device) => {
  device.status = device.status === 'online' ? 'offline' : 'online';
  device.lastActiveTime = new Date().toLocaleString();
  ElMessage.success(`设备已${device.status === 'online' ? '连接' : '断开'}`);
};

const handleDeviceDetail = (device) => {
  ElMessage.info(`查看设备 ${device.name} 的详细信息`);
};

// MQTT管理相关数据和方法
const loading = ref(false);
const topics = ref([]);
const tables = ref([]);
const topicDialogVisible = ref(false);
const topicDialogType = ref('add');
const topicFormRef = ref(null);

const topicForm = ref({
  id: '',
  topic: '',
  description: '',
  table_name: '',
  active: true
});

const topicRules = {
  topic: [{ required: true, message: '请输入通道名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入描述信息', trigger: 'blur' }],
  table_name: [{ required: true, message: '请选择关联表', trigger: 'change' }]
};

const fetchTopics = async () => {
  loading.value = true;
  try {
    const response = await fetch('https://penglink.pcwxcn.top/api/mqtt/topics', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    const result = await response.json();
    if (result.code === 200) {
      topics.value = result.data;
    } else {
      throw new Error(result.message || '获取通道列表失败');
    }
  } catch (error) {
    // console.error('获取通道列表错误:', error);
    ElMessage.error(error.message || '获取通道列表失败');
  } finally {
    loading.value = false;
  }
};

const fetchTables = async () => {
  try {
    const response = await fetch('https://penglink.pcwxcn.top/api/data/tables', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    const result = await response.json();
    if (result.code === 200) {
      tables.value = result.data;
    } else {
      throw new Error(result.message || '获取表格列表失败');
    }
  } catch (error) {
    // console.error('获取表格列表错误:', error);
    ElMessage.error(error.message || '获取表格列表失败');
  }
};

const showEditTopicDialog = (row) => {
  topicDialogType.value = 'edit';
  topicForm.value = { ...row };
  topicDialogVisible.value = true;
};

const handleDeleteTopic = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除通道 ${row.topic} 吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await fetch(`https://penglink.pcwxcn.top/api/mqtt/topics?id=${row.id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });

    const result = await response.json();
    if (result.code === 200) {
      ElMessage.success('删除成功');
      fetchTopics();
    } else {
      throw new Error(result.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      // console.error('删除失败:', error);
      ElMessage.error(error.message || '删除失败');
    }
  }
};

onMounted(() => {
  fetchTopics();
  fetchTables();
});
</script>

<style scoped>
.connection-manager {
  padding: 20px;
}
</style>
